package com.lagou.rpc.consumer.service;

import com.alibaba.fastjson.JSON;
import com.lagou.rpc.consumer.bean.ServiceInstance;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

@Component
public class MyLb implements LoadBalancer{

    private AtomicInteger atomicInteger = new AtomicInteger(-1);

    public final int getAndIncrement(){
        //当前值
        int current;
        //要更新的值
        int next;
        //轮询算法
        do{
            current = this.atomicInteger.get();
            next = current >= 2147483647 ? 0 : current + 1;
        }while(!this.atomicInteger.compareAndSet(current,next));

        System.out.println("****next:" + next);
        return next;
    }



    @Override
    public ServiceInstance instances(List<ServiceInstance> serviceInstances) {
        //获取调用的服务器下标
        int index = getAndIncrement() % serviceInstances.size();
        //返回获取调用的服务器实例
        ServiceInstance serviceInstance = serviceInstances.get(index);
        return serviceInstance;
    }

    public static void main(String[] args) {
        MyLb lb = new MyLb();

        List<ServiceInstance> serviceInstances = new ArrayList<>();
        for(int i = 1;i<=5;i++){
            ServiceInstance instance = new ServiceInstance();
            instance.setHost("127.0.0.1");
            instance.setPort( "808" + i);
            serviceInstances.add(instance);
        }


        for(int i = 0;i<11;i++){
//            new Thread( () ->{
//                ServiceInstance serviceInstance = lb.instances(serviceInstances);
//                System.out.println(JSON.toJSONString(serviceInstance));
//            }).start();

            ServiceInstance serviceInstance = lb.instances(serviceInstances);
            System.out.println(JSON.toJSONString(serviceInstance));
        }
    }
}
